package com.smsservice.banco;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * Classe que faz conex�o com MySql Singleton
 * 
 * @author Vitor
 * 
 */
public class ConexaoBD {
	public Connection conn;
	private Statement statement;
	public static ConexaoBD db;

	private String url;// = "jdbc:mysql://192.168.0.116:3306/";
	private String dbName;// = "sms";
	private String driver;// = "com.mysql.jdbc.Driver";
	private String userName;// = "root";
	private String password;// = "123";

	private ConexaoBD(String url, String dbName, String userName, String password) throws ClassNotFoundException, InstantiationException,
			SQLException, IllegalAccessException {
		this.url = url;
		this.dbName = dbName;
		this.driver = "com.mysql.jdbc.Driver";
		this.userName = userName;
		this.password = password;

		System.err.println("url: " + this.url);
		System.err.println("db name: " + this.dbName);
		System.err.println("user name: " + this.userName);
		System.err.println("password: " + this.password);
		Class.forName(this.driver).newInstance();
		this.conn = (Connection) DriverManager.getConnection(this.url + this.dbName, this.userName, this.password);

	}

	/**
	 * 
	 * @return MysqlConnect Database connection object
	 * @throws IllegalAccessException
	 * @throws SQLException
	 * @throws InstantiationException
	 * @throws ClassNotFoundException
	 */
	public static synchronized ConexaoBD getDbCon(String url, String dbName, String userName, String password) throws ClassNotFoundException,
			InstantiationException, SQLException, IllegalAccessException {
		if (db == null) {
			db = new ConexaoBD(url, dbName, userName, password);
		}
		return db;

	}

	/**
	 * 
	 * @param query
	 *            String The query to be executed
	 * @return a ResultSet object containing the results or null if not available
	 * @throws SQLException
	 */
	public ResultSet query(String query) throws SQLException {
		statement = db.conn.createStatement();
		ResultSet res = statement.executeQuery(query);
		return res;
	}

	/**
	 * @desc Method to insert data to a table
	 * @param insertQuery
	 *            String The Insert query
	 * @return boolean
	 * @throws SQLException
	 */
	public int insert(String insertQuery) throws SQLException {
		statement = db.conn.createStatement();
		int result = statement.executeUpdate(insertQuery);
		return result;

	}

}
